import BaseHTTPServer
import SocketServer
import threading
import routing

# Request handler
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
	def version_string(self):
		# Override BaseHTTP server string
		return 'Wython 0.1a'

	def log_message(self, *args):
		# Dummy delegation for now - to be impemented someday
		BaseHTTPServer.BaseHTTPRequestHandler.log_message(self, *args)
		pass

	def do_GET(self):
		# GET request
		self.processRequest()

	def do_POST(self):
		# POST request
		self.processRequest()

	def processRequest(self):
		# All GET and POST requests go here
		self.server_version = self.version_string()
		# Client environment
		env = {
			'remote_addr'		:	self.client_address[0],
			'remote_port'		:	self.client_address[1],
			'remote_str'		:	self.address_string(),
			'command'			:	self.command,
			'url'				:	self.path,
			'headers'			:	self.headers,
			'request_version'	:	self.request_version,
			'first_line'		:	'%s %s %s' % (self.command, self.path, self.request_version),
			'server_version'	:	self.server_version,
			'sys_version'		:	self.sys_version,
			'in'				:	self.rfile,
			'out'				:	self.wfile,
			'_request'			:	self,
			'_headersSent'		:	False
		}

		# Route request to appropriate controller
		self.server.router.route(self.server.root, self.path, env)


# Threaded server class proto
class ThreadedServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
	pass

# Threaded server class
class Server(ThreadedServer):
	def __init__(self, root, routes):
		self.address = ('', 8000)
		self.root = root
		self.router = routing.Router(routes)
		# Process requests with 'Handler' class
		ThreadedServer.__init__(self, self.address, Handler)

	def serve(self):
		# Here we go!
		self.serve_forever()
